package dev.entao.travel

import dev.entao.base.substr
import dev.entao.core.HttpService
import java.io.File

data class CodeLabel(val code: String, val label: String) : Comparable<CodeLabel> {
    override fun compareTo(other: CodeLabel): Int {
        return this.code.compareTo(other.code)
    }

    override fun equals(other: Any?): Boolean {
        if (other is CodeLabel) return this.code == other.code
        return false
    }

    override fun hashCode(): Int {
        return code.hashCode()
    }

    override fun toString(): String {
        return "$code=$label"
    }
}

object AreaStorage {
    //京,津,沪,渝,台,港,澳
    val zhixiaSet = setOf("11", "12", "31", "50", "71", "81", "82")
    val gangAoTai = setOf("71", "81", "82")
    private val all: ArrayList<CodeLabel> = ArrayList(3600)

    private val allProvince: List<CodeLabel> by lazy {
        all.filter { it.code.endsWith("0000") }
    }
    private val allCity: List<CodeLabel> by lazy {
        all.filter { it.code.endsWith("00") && !it.code.endsWith("0000") }
    }
    private val allCountry: List<CodeLabel> by lazy {
        all.filter { !it.code.endsWith("00") }
    }

    val provinceList: List<CodeLabel> get() = allProvince

    fun citiesOfProvince(code: String): List<CodeLabel> {
        val privCode = code.substr(0, 2)
        if (privCode in zhixiaSet) {
            return listOf(provinceList.first { it.code == code })
        }
        return allCity.filter { it.code.startsWith(privCode) }
    }

    fun countryOfCity(code: String): List<CodeLabel> {
        val privCode = code.substr(0, 2)
        if (privCode in gangAoTai) {
            return listOf(provinceList.first { it.code == code })
        }
        if (privCode in zhixiaSet) {
            return allCountry.filter { it.code.startsWith(privCode) }
        }
        val cityCode = code.substr(0, 4)
        return allCountry.filter { it.code.startsWith(cityCode) }
    }

    fun load(service: HttpService, path: String = "area.txt") {
        all.clear()
        val file = File(service.appDir, path)
        val lines = file.readLines()
        for (line in lines) {
            if (line.isEmpty()) continue
            val p = line.split(':')
            if (p.size != 2) continue
            val code = p[0].trim()
            val name = p[1].trim()
            all += CodeLabel(code, name)
        }
    }
}